package org.aplikator.server.descriptor;

import java.util.ArrayList;
import java.util.List;

import org.aplikator.client.descriptor.PanelDTO;
import org.aplikator.client.descriptor.WidgetDTO;
import org.aplikator.server.Context;

public class Panel implements Widget {

    private List<Widget> children = new ArrayList<Widget>();
    private boolean frame = false;
    private boolean vertical = false;

    public Panel(boolean vertical) {
        this.vertical = vertical;
    }

    public WidgetDTO getWidgetDescriptor(Context ctx) {
        PanelDTO desc = new PanelDTO(vertical);
        desc.setFrame(frame);
        for (Widget child : children) {
            desc.addChild(child.getWidgetDescriptor(ctx));
        }
        return desc;
    }

    public static Panel row(){
        return new Panel(false);
    }

    public static Panel column(){
        return new Panel(true);
    }

    public static Panel row(Object... children){
        Panel retval = new Panel(false);
        return retval.add(children);
    }

    public static Panel column(Object... children){
        Panel retval = new Panel(true);
        return retval.add(children);
    }


    public Panel add(Widget child) {
        if (child != null){
            children.add(child);
        }
        return this;
    }

    public Panel add(Property<?> property ){
        return add(property.widget());
    }

    private Panel add(Object... children){
        for (Object o : children){
            if (o instanceof Widget){
                add((Widget)o);
            }else if (o instanceof Property){
                add((Property<?>)o);
            }
        }
        return this;
    }

    public void registerProperties(Form form) {
        for (Widget child : children) {
            child.registerProperties(form);
        }
    }

    public boolean isFrame() {
        return frame;
    }

    public Panel setFrame(boolean frame) {
        this.frame = frame;
        return this;
    }

}